package cn.com.joycode.nimble.admin.security.authentication;

import cn.com.joycode.nimble.admin.security.configuration.NimbleAdminWebSecurityConfigurerAdapter;
import cn.com.joycode.nimble.core.message.NbMsg;
import cn.com.joycode.nimble.core.message.NbMsgBuilder;
import cn.com.joycode.nimble.web.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class NimbleAdminAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private NbMsgBuilder nbMsgBuilder;

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info("匿名访问受限:{}", httpServletRequest.getRequestURI());
        if (!ServletUtil.isJsonRequest(httpServletRequest)) {
            redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, NimbleAdminWebSecurityConfigurerAdapter.LOGIN_URL);
            return;
        }
        NbMsg apiRsp = nbMsgBuilder.buildFailResponse();
        apiRsp.setMsgSubError("401", "拒绝访问,请重新登录");
        apiRsp.put("uri", httpServletRequest.getRequestURI());
        ServletUtil.writeResponse(httpServletResponse, HttpStatus.UNAUTHORIZED.value(), apiRsp);

    }
}
